<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增项目</title>
    <script src="common.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }
        .container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            width: 100%;
            margin-top: 20px;
        }
        h1 {
            text-align: center;
            color: #333;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
        }
        select,input[type="text"],
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        textarea {
            resize: vertical;
            min-height: 100px;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            width: 100%;
        }
        button:hover {
            background-color: #0056b3;
        }
        .button-group {
            display: flex;
            flex-wrap: wrap;
            gap: 10px; /* 按钮之间的间距 */
            margin-top: 20px;
        }

        .button-group button {
            flex: 1; /* 按钮自适应宽度 */
            min-width: 120px; /* 最小宽度，防止过小 */
        }
        
        #message-area {
                position: fixed;
                top: 20px;
                right: 20px;
                z-index: 1000;
                display: flex;
                flex-direction: column;
                gap: 10px; /* Space between messages */
            }
            .message {
                padding: 10px 20px;
                border-radius: 5px;
                font-size: 16px;
                color: white;
                opacity: 1;
                transition: opacity 0.5s ease-in-out;
            }
            .message.hide {
                opacity: 0;
            }
            .message.success {
                background-color: #28a745;
            }
            .message.error {
                background-color: #dc3545;
            }
            .message.gray {
                background-color: gray;
            }
    </style>
</head>
<body>
    <div id="message-area"></div>
    <div class="container">
        <form id="newProjectForm">
            <div class="form-group">
                <label for="name">项目名称:</label>
                <input type="text" id="name" name="name" required>
            </div>
            <div class="form-group">
                <label for="textContent">内容:</label>
                <textarea id="textContent" name="textContent"></textarea>
            </div>
            
            <div class="form-group">
                <label for="textContent">讲述人:</label>
                <select name="speaker_id" id="speaker_id"></select>
            </div>
            <div class="button-group">
                <button type="submit" id="createProjectBtn">创建项目</button>
                <button type="button" id="extractRolesBtn" style="display: none;">提取角色</button>
                <button type="button" id="autoSceneBtn" style="display: none;">自动分镜</button>
            </div>
        </form>
    </div>

    <script>
        let currentProjectId = null;

        let ws = getWebSocket()
        ws.onopen = function(event) {
            console.log('WebSocket 连接成功');
        };

        ws.onmessage = function(event) {
            console.log('收到 WebSocket 消息:', event.data);
            const message = JSON.parse(event.data);
            if (message.code === 1) {
                showMessage(message.msg || '操作成功', 'success');
                // 项目创建成功后，隐藏创建项目按钮，显示其他按钮
                document.getElementById('createProjectBtn').style.display = 'none';
                document.getElementById('extractRolesBtn').style.display = 'block';
                document.getElementById('autoSceneBtn').style.display = 'block';

                // 如果返回了 projectId，存储起来以便后续操作
                if (message.data && message.data.projectId) {
                    currentProjectId = message.data.projectId;
                }
            } else if (message.code === -1) {
                showMessage(message.msg || '操作失败', 'error');
            } else if (message.code === 0) {
                showMessage(message.msg || '处理中...', 'gray');
            } else if (message.msg) {
                showMessage(message.msg, 'gray');
            }
        };

        ws.onerror = function(error) {
            console.error('WebSocket 错误:', error);
            showMessage('WebSocket 连接错误，请尝试重新连接', 'error');
        };

        ws.onclose = function(event) {
            console.log('WebSocket 连接关闭:', event.code, event.reason);
            showMessage('WebSocket 连接已关闭，正在尝试重新连接...', 'gray');
            if (!reconnectInterval) {
                reconnectInterval = setInterval(connectWebSocket, 5000); // 每5秒尝试重连
            }
        };

        document.getElementById('newProjectForm').addEventListener('submit', async function(event) {
            event.preventDefault();

            const name = document.getElementById('name').value;
            const textContent = document.getElementById('textContent').value;
            const speaker_id = document.getElementById('speaker_id').value;

            try {
                // 使用WebSocket发送数据
                if (ws.readyState !== WebSocket.OPEN) {
                    showMessage('WebSocket连接未建立或已关闭。', 'error');
                    return;
                }

                const message = {
                    action: '1', // 对应后端 taskAddHandler
                    data: {
                        name: name,
                        textContent: textContent,
                        speakerId: speaker_id,
                        status: 0 // 默认状态
                    }
                };
                ws.send(JSON.stringify(message));

                // 暂时显示成功消息，等待后端确认
                showMessage('正在创建项目...', 'gray');
            } catch (error) {
                showMessage('创建项目失败: ' + error.message, 'error');
            }
        });

        document.getElementById('extractRolesBtn').addEventListener('click', function() {
            if (ws.readyState === WebSocket.OPEN) {
                // 假设后端处理提取角色的 action 为 'extract_roles'
                ws.send(JSON.stringify({ action: 'extract_roles', data:{project_id: currentProjectId+"" }}));
                showMessage('正在提取角色...', 'gray');
            } else {
                showMessage('WebSocket连接未建立或已关闭。', 'error');
            }
        });

        document.getElementById('autoSceneBtn').addEventListener('click', function() {
            if (ws.readyState === WebSocket.OPEN) {
                // 假设后端处理自动分镜的 action 为 'auto_scene'
                ws.send(JSON.stringify({ action: 'auto_scene', data:{project_id: currentProjectId+"" }}));
                showMessage('正在自动分镜...', 'gray');
            } else {
                showMessage('WebSocket连接未建立或已关闭。', 'error');
            }
        });

        // Function to load speakers into the dropdown
        function loadSpeakers() {
            fetch('/speaker/queryAll') // Assuming this is your API endpoint for speakers
                .then(response => response.json())
                .then(data => {
                    const speakerSelect = document.getElementById('speaker_id');
                    speakerSelect.innerHTML = ''; // Clear existing options
                    if (data.code === 0 && data.data) {
                        data.data.forEach(speaker => {
                            const option = document.createElement('option');
                            option.value = speaker.id;
                            option.textContent = speaker.name;
                            speakerSelect.appendChild(option);
                        });
                    } else {
                        console.error('Failed to load speakers:', data.msg);
                        showMessage('加载讲述人列表失败', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error fetching speakers:', error);
                    showMessage('加载讲述人列表失败', 'error');
                });
        }

        // Load speakers when the page loads
        document.addEventListener('DOMContentLoaded', loadSpeakers);
    </script>
</body>
</html>